using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.TextMining.IFilter
{
    public class FileFilterWorker:IWorker
    {
        private Thread _WorkerThread;
        private FileContentSearchInstruction _Instruction;
        private FileContentSearchOutput _Output;
        private Guid _TicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return this._Output; }
        }

        public Type ComponentType
        {
            get { return typeof(FileContentSearchComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (FileContentSearchInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (FileContentSearchInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if(this.WorkerStartedEvent !=null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.SearchFolder();
        }

        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.SearchFolder));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if(this.WorkerCancelledEvent!=null)
            {
                this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region search
        private void SearchFolder()
        {
            try
            {
                List<string> fileReturnedFromSearch=new List<string>();
                if(this._Instruction.SourceFilePaths ==null || this._Instruction.SourceFilePaths.Count==0)
                {
                    throw new Exception("Unable to find any files in folder");
                }

                int processed = 0;
                foreach(string filePath in this._Instruction.SourceFilePaths)
                {
                    try
                    {
                        bool matched =
                            this.SearchFileForPattern(filePath, this._Instruction.FileNamePattern,
                                                      this._Instruction.StringMatchOption);
                        if(matched)
                            fileReturnedFromSearch.Add(filePath);

                        processed++;
                        if(this.WorkerStatusChangedEvent !=null)
                        {
                            string msg =
                                string.Format("Finished scanning file {0}. Processed {1} of {2} files",
                                              Path.GetFileName(filePath),
                                              processed,
                                              this._Instruction.SourceFilePaths.Count);
                            int percent = (processed*100)/this._Instruction.SourceFilePaths.Count;
                            this.WorkerStatusChangedEvent(this._TicketID, this.GetType(), this._Instruction, this.WorkflowName, this.ComponentName, msg,
                                                          percent);
                        }
                    }
                    catch(Exception ex1)
                    {
                        if(this.WorkerErredEvent !=null)
                        {
                            this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex1.ToString(),true);
                        }
                    }
                }
                this._Output =
                        new FileContentSearchOutput(this._Instruction.OwnerComponentID, this._TicketID,
                                                    fileReturnedFromSearch);
                    
                if(this.WorkerFinishedEvent!=null)
                {
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }

        private bool SearchFileForPattern(string filePath, string pattern, StringMatchType stringMatchOp)
        {
            FilterReader reader=new FilterReader(filePath);
            string fileContent = reader.ReadToEnd();
            reader.Close();
            if(stringMatchOp==StringMatchType.RegexMatch)
            {
                Regex regex=new Regex(pattern,RegexOptions.IgnoreCase);
                Match match = regex.Match(fileContent);
                if (match.Success)
                    return true;
                else
                    return false;
            }
            else
            {
                if (fileContent.ToLower().IndexOf(pattern.ToLower()) >= 0)
                    return true;
                else
                    return false;
            }
        }
        #endregion
    }
}
